package ernie.server.context;

import java.io.File;
import java.io.IOException;

import misc.GifDataStream;
import misc.HTMLStringStream;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import ernie.pages.Error404Page;
import ernie.pages.FilePage;
import ernie.pages.Page;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 12:04:19 PM - Nov 25, 2011
 */

public class FileContext implements HttpHandler {
    private final File root;

    public FileContext(File root) {
        this.root = root;
    }

    @Override
    public void handle(HttpExchange t) {
        try {
            String page = t.getRequestURI().toString();
            page = page.substring(page.lastIndexOf('/') + 1);
            File f = new File(root, page);
            if (f.exists()) {
                if (page.endsWith(".gif")) {
                    GifDataStream gst = new GifDataStream(t);
                    gst.write(f);
                    gst.close();
                } else {
                    HTMLStringStream hss = new HTMLStringStream(t);
                    Page filepage = new FilePage(root, page);
                    hss.write(filepage.getContent());
                    hss.close();
                }
            } else {
                HTMLStringStream hss = new HTMLStringStream(t, 404);
                hss.write(new Error404Page().getContent());
            }
        } catch (IOException ioe) {
        }
    }
}
